package cn.tedu.charging.order.webSocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: Miyako
 * @Date: 2024-10-27-16:48
 * @Description:
 */
@Slf4j
@Component
@ServerEndpoint("/ws/server/{userId}")
public class WebsocketServer {


    /**
     * @param:
     * @return:
     * @description: 本地map
     **/
    private static ConcurrentHashMap<Integer,Session> sessionMap = new ConcurrentHashMap();




/**
 * @param: [userId, message]
 * @return: java.lang.Boolean
 * @description: 消息发送方法
 **/
public Boolean sendMessage (Integer userId , String message){
    log.error("正在想用户{}发送消息",userId);
    Session session = sessionMap.get(userId);
    if (session != null){
        try {
            //发送信息
            session.getBasicRemote().sendText(message);
            return true;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }else {
        log.error("用户{}已下线",userId);
    }
    return false;
}






        /**
         * @param message
         * @param session
         * @return: void
         * @description: 消息到达 类似MQtt 的messageArrived  设备消息到达服务端
         *
         **/
    @OnMessage
    public void onMessage (String message ,Session session){

    }
    
    /**
     * @param: [session, throwable]
     * @return: void
     * @description: 出现问题调用此方法
     **/
    @OnError
    public void  onError (Session session , Throwable throwable){
        log.error("报错");
    }

    @OnClose
    public void onClose (Session session , @PathParam("userId") Integer userId){

        sessionMap.remove(userId);
        log.debug("用户:{}下线",userId);
    }
    /**
     * @param: [session, userId]  用户id 和 其对应的session
     * @return: void
     * @description: 建立接连后  类似
     **/

    @OnOpen
    public void OnOpen (Session session , @PathParam("userId") Integer userId){
        log.debug("建立连接咯");
        sessionMap.put(userId,session);
    }

}
